<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Canvas画布 | 小李博客</title><meta name="keywords" content="Canvas"><meta name="author" content="小李博客"><meta name="copyright" content="小李博客"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Canvas简介 HTML5&lt;canvas&gt;标签用于绘制图像(通过脚本，通常是JavaScript ) 不过，&lt;canvas&gt;元素本身并没有绘制能力(它仅仅是图形的容器) ，必须使用脚本来完成实际的绘图任务 getContext()方法可返回一个对象，该对象提供了用于在画布上绘图的方法和属性 提供完整的getContext(&quot;2d&quot;)对象的属性和方法，可">
<meta property="og:type" content="article">
<meta property="og:title" content="Canvas画布">
<meta property="og:url" content="http://xiaoliblog.cn/page/Canvas.html">
<meta property="og:site_name" content="小李博客">
<meta property="og:description" content="Canvas简介 HTML5&lt;canvas&gt;标签用于绘制图像(通过脚本，通常是JavaScript ) 不过，&lt;canvas&gt;元素本身并没有绘制能力(它仅仅是图形的容器) ，必须使用脚本来完成实际的绘图任务 getContext()方法可返回一个对象，该对象提供了用于在画布上绘图的方法和属性 提供完整的getContext(&quot;2d&quot;)对象的属性和方法，可">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/xiaoliblog/image@76e609149105acb43a9f47548c4cdc694358041d/2021/02/24/7a395219eedbe9cb0204f24089256030.png">
<meta property="article:published_time" content="2021-02-24T01:24:00.459Z">
<meta property="article:modified_time" content="2021-04-25T13:21:31.691Z">
<meta property="article:author" content="小李博客">
<meta property="article:tag" content="Canvas">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/xiaoliblog/image@76e609149105acb43a9f47548c4cdc694358041d/2021/02/24/7a395219eedbe9cb0204f24089256030.png"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png"><link rel="canonical" href="http://xiaoliblog.cn/page/Canvas"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: {"appId":"RTG4CPNBLJ","apiKey":"f1745bdad68ceec57653b78244fe332c","indexName":"MyBlogIndex","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":100,"languages":{"author":"作者: 小李博客","link":"链接: ","source":"来源: 小李博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'mediumZoom',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-center"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-04-25 21:21:31'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="/css/MyStyle/MyStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="/css/MyStyle/tagStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/zykjofficial/zykjresource@master/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/plugins.min.css" media="defer" onload="this.media='all'"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="小李博客" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">小李博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">Canvas画布</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-02-24T01:24:00.459Z" title="发表于 2021-02-24 09:24:00">2021-02-24</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-04-25T13:21:31.691Z" title="更新于 2021-04-25 21:21:31">2021-04-25</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Web%E5%89%8D%E7%AB%AF/">Web前端</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Web%E5%89%8D%E7%AB%AF/%E5%89%8D%E7%AB%AF%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">前端学习笔记</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>21分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Canvas画布"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div><article class="post-content" id="article-container"><h1 id="Canvas简介"><a href="#Canvas简介" class="headerlink" title="Canvas简介"></a>Canvas简介</h1><ul>
<li>HTML5<code>&lt;canvas&gt;</code>标签用于绘制图像(通过脚本，通常是JavaScript )</li>
<li>不过，<code>&lt;canvas&gt;</code>元素本身并没有绘制能力(它仅仅是图形的容器) ，必须使用脚本来完成实际的绘图任务</li>
<li><code>getContext()</code>方法可返回一个对象，该对象提供了用于在画布上绘图的方法和属性</li>
<li>提供完整的<code>getContext(&quot;2d&quot;)</code>对象的属性和方法，可用于在画布上绘制文本、线条、矩形、圆形等等</li>
<li>SVG基于XML，放大不会失真，但性能差于Canvas</li>
<li>Canvas相关属性和方法请戳👉<a target="_blank" rel="noopener" href="https://www.w3school.com.cn/tags/html_ref_canvas.asp">HTML 5 Canvas 参考手册
</a>||<a target="_blank" rel="noopener" href="https://www.runoob.com/w3cnote/html5-canvas-intro.html">学习 HTML5 Canvas 这一篇文章就够了</a></li>
</ul>
<h2 id="Canvas实例"><a href="#Canvas实例" class="headerlink" title="Canvas实例"></a>Canvas实例</h2><ul>
<li><strong>Canvas三要素</strong><ul>
<li><code>id</code>：作为唯一的标识</li>
<li><code>width</code>：画布内容宽度的像素大小（与style的宽度和高度是有区别的）</li>
<li><code>height</code>：画布内容高度的像素大小</li>
</ul>
</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;500&quot;</span> <span class="attr">height</span>=<span class="string">&quot;500&quot;</span>&gt;</span></span><br><span class="line">   这里的内容，正常的画布是不显示的，你的浏览器不支持Canvas</span><br><span class="line"><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br></pre></td></tr></table></figure>

<div class="note success simple"><p>Canvas相当于定义一个画布，而JavaScript就是画笔</p>
</div>

<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;500&quot;</span> <span class="attr">height</span>=<span class="string">&quot;500&quot;</span>&gt;</span></span><br><span class="line">   这里的内容，正常的画布是不显示的，你的浏览器不支持Canvas</span><br><span class="line"><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="comment">//1. 找到画布对象</span></span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="built_in">console</span>.log([canvas]);</span></span><br><span class="line"><span class="javascript">   <span class="comment">//2. 上下文对象（画笔）</span></span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> ctx= canvas.getContext(<span class="string">&quot;2d&quot;</span>); <span class="comment">//画2d</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">//var ctx= canvas.getContext(&quot;webgl&quot;); 画3d</span></span></span><br><span class="line"><span class="javascript">   <span class="built_in">console</span>.log(ctx); <span class="comment">//通过F12可以查询相关属性和方法</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">//3. 绘制路径</span></span></span><br><span class="line">   ctx.rect(50,50,300,300);</span><br><span class="line"><span class="javascript">   <span class="comment">//4. 填充</span></span></span><br><span class="line"><span class="javascript">   ctx.fillStyle=<span class="string">&quot;skyblue&quot;</span>;  <span class="comment">//设置样式</span></span></span><br><span class="line"><span class="javascript">   ctx.fill();  <span class="comment">//最终渲染</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">//5. 描边，渲染路径</span></span></span><br><span class="line"><span class="javascript">   ctx.lineWidth = <span class="number">20</span>; <span class="comment">//线段宽度</span></span></span><br><span class="line"><span class="javascript">   ctx.strokeStyle=<span class="string">&quot;red&quot;</span>;</span></span><br><span class="line">   ctx.stroke();</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@51f7e1bf5a2c6a13315e28a476f86af07f3b5041/2021/02/24/a24e0695bcfd42ee487610a42f8bd6e3.png"></p>
<h1 id="Canvas基础绘制"><a href="#Canvas基础绘制" class="headerlink" title="Canvas基础绘制"></a>Canvas基础绘制</h1><h2 id="路径"><a href="#路径" class="headerlink" title="路径"></a>路径</h2><table>
<thead>
<tr>
<th align="center">方法</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>fill()</code></td>
<td align="center">填充当前绘图（路径）</td>
</tr>
<tr>
<td align="center"><code>stroke()</code></td>
<td align="center">绘制已定义的路径</td>
</tr>
<tr>
<td align="center"><code>beginPath()</code></td>
<td align="center">起始一条路径，或重置当前路径</td>
</tr>
<tr>
<td align="center"><code>moveTo()</code></td>
<td align="center">把路径移动到画布中的指定点，不创建线条</td>
</tr>
<tr>
<td align="center"><code>closePath()</code></td>
<td align="center">创建从当前点回到起始点的路径</td>
</tr>
<tr>
<td align="center"><code>lineTo()</code></td>
<td align="center">添加一个新点，然后在画布中创建从该点到最后指定点的线条</td>
</tr>
<tr>
<td align="center"><code>clip()</code></td>
<td align="center">从原始画布剪切任意形状和尺寸的区域</td>
</tr>
<tr>
<td align="center"><code>quadraticCurveTo()</code></td>
<td align="center">创建二次贝塞尔曲线</td>
</tr>
<tr>
<td align="center"><code>bezierCurveTo()</code></td>
<td align="center">创建三次方贝塞尔曲线</td>
</tr>
<tr>
<td align="center"><code>arc()</code></td>
<td align="center">创建弧/曲线（用于创建圆形或部分圆）</td>
</tr>
<tr>
<td align="center"><code>arcTo()</code></td>
<td align="center">创建两切线之间的弧/曲线</td>
</tr>
<tr>
<td align="center"><code>isPointInPath()</code></td>
<td align="center">如果指定的点位于当前路径中，则返回 true，否则返回 false</td>
</tr>
</tbody></table>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;500&quot;</span> <span class="attr">height</span>=<span class="string">&quot;500&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> ctx= canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span></span><br><span class="line"><span class="javascript">   ctx.beginPath(); <span class="comment">//设置开始路径</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">//设置绘制的起始点</span></span></span><br><span class="line">   ctx.moveTo(50,50);</span><br><span class="line"><span class="javascript">   <span class="comment">//设置经过某个位置</span></span></span><br><span class="line">   ctx.lineTo(50,300);</span><br><span class="line">   ctx.lineTo(300,100);</span><br><span class="line"><span class="javascript">   ctx.closePath();  <span class="comment">//设置结束路径，会关闭路径即连接起始点不会出现连笔</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">//绘制路径</span></span></span><br><span class="line"><span class="javascript">   ctx.strokeStyle=<span class="string">&quot;skyblue&quot;</span>;</span></span><br><span class="line">   ctx.lineWidth=10;</span><br><span class="line">   ctx.stroke();</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@cfbb748d6744437e6357de1c317141e6bd8ff8ca/2021/02/24/e28cecdaae84a564573bd4ef66b87e87.png"></p>
<h2 id="线段"><a href="#线段" class="headerlink" title="线段"></a>线段</h2><table>
<thead>
<tr>
<th align="center">属性</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>lineCap</code></td>
<td align="center">设置或返回线条的结束端点样式</td>
</tr>
<tr>
<td align="center"><code>lineJoin</code></td>
<td align="center">设置或返回两条线相交时，所创建的拐角类型</td>
</tr>
<tr>
<td align="center"><code>lineWidth</code></td>
<td align="center">设置或返回当前的线条宽度</td>
</tr>
<tr>
<td align="center"><code>miterLimit</code></td>
<td align="center">设置或返回最大斜接长度</td>
</tr>
</tbody></table>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;500&quot;</span> <span class="attr">height</span>=<span class="string">&quot;500&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> ctx= canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">   ctx.beginPath(); <span class="comment">//设置开始路径</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">//设置绘制的起始点</span></span></span><br><span class="line">   ctx.moveTo(50,50);</span><br><span class="line"><span class="javascript">   <span class="comment">//设置经过某个位置</span></span></span><br><span class="line">   ctx.lineTo(50,300);</span><br><span class="line">   ctx.lineTo(300,100);</span><br><span class="line">   ctx.lineTo(300,250);</span><br><span class="line"><span class="javascript">   ctx.closePath();  <span class="comment">//设置结束路径，会关闭路径不会出现连笔</span></span></span><br><span class="line"></span><br><span class="line"><span class="javascript">   <span class="comment">//绘制路径</span></span></span><br><span class="line"><span class="javascript">   ctx.lineCap=<span class="string">&quot;round&quot;</span>; <span class="comment">//设置起始路径线段设置为圆角</span></span></span><br><span class="line"><span class="javascript">   ctx.lineJoin=<span class="string">&quot;round&quot;</span>; <span class="comment">//设置拐角线段设置为圆角</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">// ctx.miterLimit = 2; //设置最大斜接长度，设置多少就会砍掉多少像素</span></span></span><br><span class="line"><span class="javascript">   ctx.strokeStyle=<span class="string">&quot;skyblue&quot;</span>;</span></span><br><span class="line">   ctx.lineWidth=20;</span><br><span class="line">   ctx.stroke();</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@c148bab632c382b068ea094433f4e6cd776984c4/2021/02/24/83e1a58e782124935cf2cd61147a1de2.png"></p>
<h2 id="圆"><a href="#圆" class="headerlink" title="圆"></a>圆</h2><ul>
<li>绘制圆形使用<code>arc(x,y,r,start,stop)</code>方法</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;600&quot;</span> <span class="attr">height</span>=<span class="string">&quot;600&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">   <span class="comment">// 默认false顺时针画圆可不写，true为逆时针</span></span></span><br><span class="line"><span class="javascript">   ctx.arc(<span class="number">300</span>, <span class="number">300</span>, <span class="number">100</span>, <span class="number">0</span>, <span class="number">2</span>*<span class="built_in">Math</span>.PI,<span class="literal">true</span>); <span class="comment">//(cx,cy,r,开始角度，结束角度，顺时针或者逆时针)</span></span></span><br><span class="line"><span class="javascript">   ctx.fillStyle=<span class="string">&quot;skyblue&quot;</span>;</span></span><br><span class="line">   ctx.fill();</span><br><span class="line">   ctx.stroke();</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@0dbc528050fff8486b753acd6faec7fdbaa4d76b/2021/02/24/20a3565faa17036a9cef08eac0ba387a.png"></p>
<h2 id="文本"><a href="#文本" class="headerlink" title="文本"></a>文本</h2><table>
<thead>
<tr>
<th align="center">属性</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>font</code></td>
<td align="center">设置或返回文本内容的当前字体属性</td>
</tr>
<tr>
<td align="center"><code>textAlign</code></td>
<td align="center">设置或返回文本内容的当前对齐方式</td>
</tr>
<tr>
<td align="center"><code>textBaseline</code></td>
<td align="center">设置或返回在绘制文本时使用的当前文本基线</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th align="center">方法</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>fillText()</code></td>
<td align="center">在画布上绘制“被填充的”文本</td>
</tr>
<tr>
<td align="center"><code>strokeText()</code></td>
<td align="center">在画布上绘制文本（无填充）</td>
</tr>
<tr>
<td align="center"><code>measureText()</code></td>
<td align="center">返回包含指定文本宽度的对象</td>
</tr>
</tbody></table>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;600&quot;</span> <span class="attr">height</span>=<span class="string">&quot;600&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="built_in">console</span>.log(ctx);</span></span><br><span class="line"><span class="javascript">   <span class="comment">//设置字号和字体</span></span></span><br><span class="line"><span class="javascript">   ctx.font = <span class="string">&quot;50px 微软雅黑&quot;</span>;</span></span><br><span class="line"><span class="javascript">   <span class="comment">// 设置样式 （这些属性都可以输出ctx在F12中查看）</span></span></span><br><span class="line"><span class="javascript">   ctx.shadowBlur = <span class="number">20</span>; <span class="comment">//阴影的模糊度</span></span></span><br><span class="line"><span class="javascript">   ctx.shadowColor = <span class="string">&quot;rgba(0,0,0,1)&quot;</span>; <span class="comment">//阴影的颜色</span></span></span><br><span class="line"><span class="javascript">   ctx.shadowOffsetX = <span class="number">10</span>; <span class="comment">//阴影水平偏移量</span></span></span><br><span class="line"><span class="javascript">   ctx.shadowOffsetY = <span class="number">10</span>; <span class="comment">//阴影垂直偏移量</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">// 设置文字填充 fillText(text,x,y);</span></span></span><br><span class="line"><span class="javascript">   ctx.fillText(<span class="string">&quot;Hello World&quot;</span>, <span class="number">100</span>, <span class="number">100</span>);</span></span><br><span class="line"><span class="javascript">   <span class="comment">// 设置描边无填充内容</span></span></span><br><span class="line"><span class="javascript">   ctx.strokeText(<span class="string">&quot;描边内容&quot;</span>, <span class="number">100</span>, <span class="number">200</span>);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@17fa9051d3e231e8d32e735d7246bab3bc9eef50/2021/02/24/f86d5a28b5b317b141556945d2824db6.png"></p>
<ul>
<li><strong>增加定时器实现弹幕效果</strong></li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = <span class="number">600</span>;</span><br><span class="line"><span class="built_in">setInterval</span>(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">   <span class="comment">//清空画布</span></span><br><span class="line">   ctx.clearRect(<span class="number">0</span>, <span class="number">0</span>, <span class="number">600</span>, <span class="number">600</span>);</span><br><span class="line">   x -= <span class="number">10</span>;</span><br><span class="line">   <span class="function"><span class="title">if</span>(<span class="params">x&lt;-<span class="number">100</span></span>)</span>&#123;</span><br><span class="line">      x=<span class="number">600</span>;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">// 设置文字填充 fillText(text,x,y);</span></span><br><span class="line">   ctx.fillText(<span class="string">&quot;Hello World&quot;</span>, x, <span class="number">100</span>);</span><br><span class="line">   <span class="comment">// 设置描边无填充内容</span></span><br><span class="line">      ctx.strokeText(<span class="string">&quot;描边内容&quot;</span>, x, <span class="number">200</span>);</span><br><span class="line">   &#125;, <span class="number">30</span>);</span><br></pre></td></tr></table></figure>

<h1 id="Canvas常见操作"><a href="#Canvas常见操作" class="headerlink" title="Canvas常见操作"></a>Canvas常见操作</h1><h2 id="图像绘制"><a href="#图像绘制" class="headerlink" title="图像绘制"></a>图像绘制</h2><ul>
<li>在画布上定位图像<br>  <code>context.drawImage(图片对象,x位置,y位置);</code></li>
<li>在画布上定位图像，并规定图像的宽度和高度<br>  <code>context.drawImage(图片对象,x位置,y位置,width,height);</code></li>
<li>剪切图像，并在画布上定位被剪切的部分：<br>  <code>context.drawImage(图片对象,图像裁剪的位置x,图像裁剪的位置y,裁剪的宽度,裁剪的高度,x,y,width,height);</code></li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;600&quot;</span> <span class="attr">height</span>=<span class="string">&quot;600&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="comment">//绘制图像</span></span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> img = <span class="keyword">new</span> Image();</span></span><br><span class="line"><span class="javascript">   img.src = <span class="string">&quot;logo.png&quot;</span>;</span></span><br><span class="line"><span class="javascript">   <span class="comment">//图片载入数据后再绘制</span></span></span><br><span class="line"><span class="javascript">   img.onload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line">   ctx.drawImage(img,50, 50,200,200);</span><br><span class="line"><span class="javascript">   ctx.fillText(<span class="string">&quot;水印&quot;</span>,<span class="number">40</span>,<span class="number">40</span>); <span class="comment">//添加水印</span></span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@8f9c5e53390a5e24d6ee71ea27218991c21d89ad/2021/02/24/2f1fd5aa3ed6efafe46177aa1ec57fe9.png"></p>
<h2 id="视频处理"><a href="#视频处理" class="headerlink" title="视频处理"></a>视频处理</h2><ul>
<li>通过Canvas画视频可以防止视频被盗</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"> <span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;800&quot;</span> <span class="attr">height</span>=<span class="string">&quot;600&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line">&lt;video width=&quot;800&quot; height=&quot;600&quot; src=&quot;movie.mp4&quot; controls=&quot;controls&quot;&lt;/video&gt;</span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> video = <span class="built_in">document</span>.querySelector(<span class="string">&quot;video&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> interId;</span></span><br><span class="line"><span class="javascript">   <span class="comment">// 视频开始播放就开始一帧一帧绘制</span></span></span><br><span class="line"><span class="javascript">   video.onplay=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">   interId= <span class="built_in">setInterval</span>(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">   <span class="comment">//实现底色为黑色</span></span></span><br><span class="line">      ctx.clearRect(0,0,800,600);</span><br><span class="line">      ctx.fillRect(0,0,800,600); </span><br><span class="line">      ctx.drawImage(video,0,70,800,440);</span><br><span class="line"><span class="javascript">      <span class="comment">//加水印</span></span></span><br><span class="line"><span class="javascript">      ctx.font=<span class="string">&quot;20px 微软雅黑&quot;</span>;</span></span><br><span class="line"><span class="javascript">      ctx.strokeStyle=<span class="string">&quot;#999&quot;</span>;</span></span><br><span class="line"><span class="javascript">      ctx.strokeText(<span class="string">&quot;我是水印&quot;</span>,<span class="number">50</span>,<span class="number">50</span>);</span></span><br><span class="line"><span class="javascript">     &#125;,<span class="number">16</span>); <span class="comment">//16为最适应刷新率</span></span></span><br><span class="line">   &#125;</span><br><span class="line"><span class="javascript">   video.onpause=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">        <span class="built_in">clearInterval</span>(interId);</span></span><br><span class="line">   &#125;;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="绘制时钟"><a href="#绘制时钟" class="headerlink" title="绘制时钟"></a>绘制时钟</h2><table>
<thead>
<tr>
<th align="center">方法</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>scale()</code></td>
<td align="center">缩放当前绘图至更大或更小</td>
</tr>
<tr>
<td align="center"><code>rotate()</code></td>
<td align="center">旋转当前绘图</td>
</tr>
<tr>
<td align="center"><code>translate()</code></td>
<td align="center">重新映射画布上的 (0,0) 位置</td>
</tr>
<tr>
<td align="center"><code>transform()</code></td>
<td align="center">替换绘图的当前转换矩阵</td>
</tr>
<tr>
<td align="center"><code>setTransform()</code></td>
<td align="center">将当前转换重置为单位矩阵。然后运行 transform()</td>
</tr>
</tbody></table>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;800&quot;</span> <span class="attr">height</span>=<span class="string">&quot;600&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span></span><br><span class="line">   </span><br><span class="line"><span class="javascript">   ctx.translate(<span class="number">300</span>,<span class="number">0</span>);  <span class="comment">//tanslate会改变整个画布坐标尺</span></span></span><br><span class="line"><span class="javascript">   ctx.rotate(<span class="built_in">Math</span>.PI/<span class="number">4</span>);  <span class="comment">//整个画布坐标旋转</span></span></span><br><span class="line"><span class="javascript">   ctx.scale(<span class="number">2</span>,<span class="number">2</span>);   <span class="comment">//x,y放大画布坐标尺</span></span></span><br><span class="line">   </span><br><span class="line"><span class="javascript">   ctx.fillStyle=<span class="string">&quot;skyblue&quot;</span>;</span></span><br><span class="line"><span class="javascript">   ctx.fillRect(<span class="number">100</span>,<span class="number">100</span>,<span class="number">300</span>,<span class="number">100</span>); <span class="comment">//直接填充一个矩形</span></span></span><br><span class="line">   </span><br><span class="line"><span class="javascript">   ctx.fillStyle=<span class="string">&quot;pink&quot;</span>;</span></span><br><span class="line">   ctx.fillRect(0,0,100,100);</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;800&quot;</span> <span class="attr">height</span>=<span class="string">&quot;600&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span></span><br><span class="line"><span class="javascript">        <span class="function"><span class="keyword">function</span> <span class="title">renderClock</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line">            ctx.clearRect(0,0,800,600);</span><br><span class="line"><span class="javascript">            ctx.save(); <span class="comment">//保留环境的状态（画笔的状态）</span></span></span><br><span class="line"><span class="javascript">            <span class="comment">//将坐标移动到画布的中央</span></span></span><br><span class="line">            ctx.translate(400, 300);</span><br><span class="line"><span class="javascript">            ctx.rotate(-<span class="number">2</span> * <span class="built_in">Math</span>.PI / <span class="number">4</span>);</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">            ctx.save();<span class="comment">//保留环境的状态（画笔的状态）</span></span></span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">//绘制表盘</span></span></span><br><span class="line">            ctx.beginPath();</span><br><span class="line"><span class="javascript">            ctx.arc(<span class="number">0</span>, <span class="number">0</span>, <span class="number">200</span>, <span class="number">0</span>, <span class="number">2</span> * <span class="built_in">Math</span>.PI);</span></span><br><span class="line"><span class="javascript">            ctx.strokeStyle = <span class="string">&quot;darkgray&quot;</span>;</span></span><br><span class="line">            ctx.lineWidth = 10;</span><br><span class="line">            ctx.stroke();</span><br><span class="line">            ctx.closePath();</span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">//绘制秒钟刻度</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">for</span> (<span class="keyword">var</span> j = <span class="number">0</span>; j &lt; <span class="number">60</span>; j++) &#123;</span></span><br><span class="line"><span class="javascript">                ctx.rotate(<span class="number">2</span> * <span class="built_in">Math</span>.PI / <span class="number">60</span>); <span class="comment">//旋转会改变坐标尺</span></span></span><br><span class="line">                ctx.beginPath();</span><br><span class="line">                ctx.moveTo(180, 0);</span><br><span class="line">                ctx.lineTo(190, 0);</span><br><span class="line">                ctx.lineWidth = 2;</span><br><span class="line"><span class="javascript">                ctx.strokeStyle = <span class="string">&quot;orangered&quot;</span>;</span></span><br><span class="line">                ctx.stroke();</span><br><span class="line">                ctx.closePath();</span><br><span class="line">            &#125;</span><br><span class="line">            ctx.restore();</span><br><span class="line">            ctx.save();</span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">//绘制时钟刻度</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">12</span>; i++) &#123;</span></span><br><span class="line"><span class="javascript">                ctx.rotate(<span class="number">2</span> * <span class="built_in">Math</span>.PI / <span class="number">12</span>); <span class="comment">//旋转会改变坐标尺</span></span></span><br><span class="line">                ctx.beginPath();</span><br><span class="line">                ctx.moveTo(180, 0);</span><br><span class="line">                ctx.lineTo(200, 0);</span><br><span class="line">                ctx.lineWidth = 10;</span><br><span class="line"><span class="javascript">                ctx.strokeStyle = <span class="string">&quot;darkgray&quot;</span>;</span></span><br><span class="line">                ctx.stroke();</span><br><span class="line">                ctx.closePath();</span><br><span class="line">            &#125;</span><br><span class="line">            ctx.restore();</span><br><span class="line">            ctx.save();</span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">// 获取时间</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> time = <span class="keyword">new</span> <span class="built_in">Date</span>();</span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> hour = time.getHours();</span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> min = time.getMinutes();</span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> sec = time.getSeconds();</span></span><br><span class="line"><span class="javascript">            <span class="comment">//如果时间是大于12的话，就减去12</span></span></span><br><span class="line">            hour = hour &gt; 12 ? hour - 12 : hour;</span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">//绘制秒针</span></span></span><br><span class="line">            ctx.beginPath();</span><br><span class="line"><span class="javascript">            <span class="comment">//根据秒针的时间进行旋转</span></span></span><br><span class="line"><span class="javascript">            ctx.rotate(<span class="number">2</span> * <span class="built_in">Math</span>.PI / <span class="number">60</span> * sec);</span></span><br><span class="line">            ctx.moveTo(-30, 0);</span><br><span class="line">            ctx.lineTo(170, 0);</span><br><span class="line">            ctx.lineWidth = 2;</span><br><span class="line"><span class="javascript">            ctx.strokeStyle = <span class="string">&quot;red&quot;</span>;</span></span><br><span class="line">            ctx.stroke();</span><br><span class="line">            ctx.closePath();</span><br><span class="line"></span><br><span class="line">            ctx.restore();</span><br><span class="line">            ctx.save();</span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">//绘制分针</span></span></span><br><span class="line">            ctx.beginPath();</span><br><span class="line"><span class="javascript">            <span class="comment">//根据分针的时间进行旋转</span></span></span><br><span class="line"><span class="javascript">            ctx.rotate(<span class="number">2</span> * <span class="built_in">Math</span>.PI / <span class="number">60</span> * min + <span class="number">2</span> * <span class="built_in">Math</span>.PI / <span class="number">3600</span> * sec);</span></span><br><span class="line">            ctx.moveTo(-20, 0);</span><br><span class="line">            ctx.lineTo(150, 0);</span><br><span class="line">            ctx.lineWidth = 3;</span><br><span class="line"><span class="javascript">            ctx.strokeStyle = <span class="string">&quot;skyblue&quot;</span>;</span></span><br><span class="line">            ctx.stroke();</span><br><span class="line">            ctx.closePath();</span><br><span class="line"></span><br><span class="line">            ctx.restore();</span><br><span class="line">            ctx.save();</span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">//绘制时针</span></span></span><br><span class="line">            ctx.beginPath();</span><br><span class="line"><span class="javascript">            <span class="comment">//根据时针的时间进行旋转</span></span></span><br><span class="line"><span class="javascript">            ctx.rotate(<span class="number">2</span> * <span class="built_in">Math</span>.PI / <span class="number">12</span> * hour + <span class="number">2</span> * <span class="built_in">Math</span>.PI / <span class="number">60</span> / <span class="number">12</span> * min + <span class="number">2</span> * <span class="built_in">Math</span>.PI / <span class="number">12</span> / <span class="number">60</span> / <span class="number">60</span> * sec);</span></span><br><span class="line">            ctx.moveTo(-10, 0);</span><br><span class="line">            ctx.lineTo(140, 0);</span><br><span class="line">            ctx.lineWidth = 6;</span><br><span class="line"><span class="javascript">            ctx.strokeStyle = <span class="string">&quot;darkgray&quot;</span>;</span></span><br><span class="line">            ctx.stroke();</span><br><span class="line">            ctx.closePath();</span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="built_in">console</span>.log(time);</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">//绘制中心小圆点</span></span></span><br><span class="line">            ctx.beginPath();</span><br><span class="line"><span class="javascript">            ctx.arc(<span class="number">0</span>, <span class="number">0</span>, <span class="number">10</span>, <span class="number">0</span>, <span class="number">2</span> * <span class="built_in">Math</span>.PI);</span></span><br><span class="line"><span class="javascript">            ctx.fillStyle = <span class="string">&quot;skyblue&quot;</span>;</span></span><br><span class="line">            ctx.fill();</span><br><span class="line">            ctx.closePath();</span><br><span class="line"></span><br><span class="line">            ctx.restore();</span><br><span class="line">            ctx.restore();</span><br><span class="line">        &#125;;</span><br><span class="line"><span class="javascript">        <span class="built_in">setInterval</span>(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line">            renderClock();</span><br><span class="line">        &#125;,1000);</span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="刮刮卡"><a href="#刮刮卡" class="headerlink" title="刮刮卡"></a>刮刮卡</h2><ul>
<li><code>globalCompositeOperation</code>：设置或返回新图像如何绘制到已有的图像上</li>
<li><code>globalCompositeOperation</code>属性设置或返回如何将一个源(新的)图像绘制到目标(已有的)的图像上</li>
<li><strong>源图像=您打算放置到画布上的绘图</strong></li>
<li><strong>目标图像=您已经放置在画布上的绘图</strong></li>
<li>属性值查看<a target="_blank" rel="noopener" href="https://www.w3school.com.cn/tags/canvas_globalcompositeoperation.asp">HTML 5 canvas globalCompositeOperation 属性</a><table>
<thead>
<tr>
<th align="center">默认值:</th>
<th align="center">source-over</th>
</tr>
</thead>
<tbody><tr>
<td align="center">JavaScript语法:</td>
<td align="center">context.globalCompositeOperation=”source-in”;</td>
</tr>
</tbody></table>
</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;800&quot;</span> <span class="attr">height</span>=<span class="string">&quot;600&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">   <span class="comment">//第一个红色矩形为目标图像</span></span></span><br><span class="line"><span class="javascript">   ctx.fillStyle = <span class="string">&quot;hotpink&quot;</span>;</span></span><br><span class="line">   ctx.fillRect(100, 100, 200, 200);</span><br><span class="line"></span><br><span class="line"><span class="javascript">   ctx.globalCompositeOperation=<span class="string">&quot;source-atop&quot;</span>;<span class="comment">//源图像位于目标图像之外的部分是不可见的</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">//默认值为source-over，源图像在目标图像之上</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">//第二个蓝色为打算放置的图像即源图像</span></span></span><br><span class="line"><span class="javascript">   ctx.fillStyle = <span class="string">&quot;deepskyblue&quot;</span>;</span></span><br><span class="line">   ctx.fillRect(200, 200, 200, 200);</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">style</span> <span class="attr">type</span>=<span class="string">&quot;text/css&quot;</span>&gt;</span></span><br><span class="line"><span class="css">        <span class="selector-id">#ggk</span> &#123;</span></span><br><span class="line">            width: 400px;</span><br><span class="line">            height: 100px;</span><br><span class="line">            position: relative;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"><span class="css">        <span class="selector-id">#ggk</span> <span class="selector-class">.jp</span> &#123;</span></span><br><span class="line">            width: 400px;</span><br><span class="line">            height: 100px;</span><br><span class="line">            position: absolute;</span><br><span class="line">            left: 0;</span><br><span class="line">            right: 0;</span><br><span class="line">            text-align: center;</span><br><span class="line">            color: cornflowerblue;</span><br><span class="line">            font-size: 50px;</span><br><span class="line">            line-height: 100px;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"><span class="css">        <span class="selector-id">#ggk</span> <span class="selector-id">#mycanvas</span> &#123;</span></span><br><span class="line">            width: 400px;</span><br><span class="line">            height: 100px;</span><br><span class="line">            position: absolute;</span><br><span class="line">            left: 0;</span><br><span class="line">            right: 0;</span><br><span class="line">        &#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;ggk&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;jp&quot;</span>&gt;</span>谢谢惠顾<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;400&quot;</span> <span class="attr">height</span>=<span class="string">&quot;100&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> ggkDom = <span class="built_in">document</span>.getElementById(<span class="string">&quot;ggk&quot;</span>);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> jpDom=<span class="built_in">document</span>.querySelector(<span class="string">&quot;.jp&quot;</span>);</span></span><br><span class="line"><span class="javascript">        <span class="comment">//画一层灰色覆盖</span></span></span><br><span class="line"><span class="javascript">        ctx.fillStyle = <span class="string">&quot;gray&quot;</span>;</span></span><br><span class="line">        ctx.fillRect(0, 0, 400, 100);</span><br><span class="line"><span class="javascript">        ctx.fillStyle = <span class="string">&quot;#fff&quot;</span>;</span></span><br><span class="line"><span class="javascript">        ctx.font = <span class="string">&quot;20px 微软雅黑&quot;</span>;</span></span><br><span class="line"><span class="javascript">        ctx.fillText(<span class="string">&quot;刮刮卡&quot;</span>, <span class="number">160</span>, <span class="number">50</span>);</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">// 鼠标按下事件，设置允许绘制isDraw=true</span></span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> isDraw = <span class="literal">false</span>;</span></span><br><span class="line"><span class="javascript">        canvas.onmousedown = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            isDraw = <span class="literal">true</span>;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">console</span>.log(isDraw);</span></span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">//移动的适合绘制圆形，将源图像内的目标内容清除掉</span></span></span><br><span class="line"><span class="javascript">        canvas.onmousemove = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span></span><br><span class="line">            if (isDraw) &#123;</span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> x = e.pageX - ggkDom.offsetLeft;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> y = e.pageY - ggkDom.offsetTop;</span></span><br><span class="line"><span class="javascript">                ctx.globalCompositeOperation = <span class="string">&quot;destination-out&quot;</span>;</span></span><br><span class="line"><span class="javascript">                ctx.arc(x, y, <span class="number">10</span>, <span class="number">0</span>, <span class="number">2</span> * <span class="built_in">Math</span>.PI); <span class="comment">//以鼠标位置为中心画圆</span></span></span><br><span class="line">                ctx.fill();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">// 鼠标抬起，不需要绘制</span></span></span><br><span class="line"><span class="javascript">        canvas.onmouseup = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            isDraw = <span class="literal">false</span>;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">console</span>.log(isDraw);</span></span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> arr = [</span></span><br><span class="line"><span class="javascript">            &#123; <span class="attr">content</span>: <span class="string">&quot;一等奖:IPhoneXs&quot;</span>, <span class="attr">p</span>: <span class="number">0.1</span> &#125;,</span></span><br><span class="line"><span class="javascript">            &#123; <span class="attr">content</span>: <span class="string">&quot;二等奖:IPad2018&quot;</span>, <span class="attr">p</span>: <span class="number">0.2</span> &#125;,</span></span><br><span class="line"><span class="javascript">            &#123; <span class="attr">content</span>: <span class="string">&quot;三等奖:HUAWEI&quot;</span>, <span class="attr">p</span>: <span class="number">0.3</span> &#125;,</span></span><br><span class="line">        ];</span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> randomNum = <span class="built_in">Math</span>.random();</span></span><br><span class="line"><span class="javascript">        <span class="built_in">console</span>.log(randomNum);</span></span><br><span class="line">        if (randomNum &lt; arr[0].p) &#123;</span><br><span class="line">            jpDom.innerHTML = arr[0].content;</span><br><span class="line">        &#125;</span><br><span class="line"><span class="javascript">        <span class="keyword">else</span> <span class="keyword">if</span> (randomNum &lt; arr[<span class="number">1</span>].p + arr[<span class="number">0</span>].p) &#123;</span></span><br><span class="line">            jpDom.innerHTML = arr[1].content;</span><br><span class="line">        &#125;</span><br><span class="line"><span class="javascript">        <span class="keyword">else</span> <span class="keyword">if</span> (randomNum &lt; arr[<span class="number">2</span>].p + arr[<span class="number">1</span>].p + arr[<span class="number">0</span>].p) &#123;</span></span><br><span class="line">            jpDom.innerHTML = arr[2].content;</span><br><span class="line">        &#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="画板"><a href="#画板" class="headerlink" title="画板"></a>画板</h2><ul>
<li>画笔功能：<ul>
<li>能够拖动鼠标在页面内绘图，能够设置画笔粗细和颜色</li>
<li>能够在任意位置绘制图形：拖动鼠标即可随意在任意位置绘制图形，并且随意定制大小</li>
</ul>
</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">style</span>&gt;</span></span><br><span class="line">        * &#123;</span><br><span class="line">            margin: 0;</span><br><span class="line">            padding: 0;</span><br><span class="line">            box-sizing: border-box;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        body &#123;</span><br><span class="line">            display: flex;</span><br><span class="line">            width: 100vw;</span><br><span class="line">            height: 100vh;</span><br><span class="line">            flex-direction: column;</span><br><span class="line">            justify-content: flex-start;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"><span class="css">        <span class="selector-class">.caidan</span> &#123;</span></span><br><span class="line">            height: 100px;</span><br><span class="line">            width: 100vw;</span><br><span class="line">            display: flex;</span><br><span class="line"><span class="css">            <span class="selector-tag">border-bottom</span>: 3<span class="selector-tag">px</span> <span class="selector-tag">solid</span> <span class="selector-id">#ccc</span>;</span></span><br><span class="line">            justify-content: space-around;</span><br><span class="line">            align-items: center;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"><span class="css">        <span class="selector-id">#mycanvas</span> &#123;</span></span><br><span class="line">            flex: 1;</span><br><span class="line">            width: 100vw;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"><span class="css">        <span class="selector-class">.btn</span> &#123;</span></span><br><span class="line">            width: 200px;</span><br><span class="line">            height: 50px;</span><br><span class="line"><span class="css">            <span class="selector-tag">border</span>: 1<span class="selector-tag">px</span> <span class="selector-tag">solid</span> <span class="selector-id">#ccc</span>;</span></span><br><span class="line">            border-radius: 20px;</span><br><span class="line">            text-align: center;</span><br><span class="line">            line-height: 50px;</span><br><span class="line">            color: green;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"><span class="css">        <span class="selector-class">.btn</span><span class="selector-class">.active</span> &#123;</span></span><br><span class="line">            box-shadow: 0 0 20px skyblue;</span><br><span class="line"><span class="css">            <span class="comment">/*发光*/</span></span></span><br><span class="line">            background-color: darkturquoise;</span><br><span class="line">            border-color: greenyellow;</span><br><span class="line">        &#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;caidan&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;btn&quot;</span> <span class="attr">id</span>=<span class="string">&quot;huabi&quot;</span>&gt;</span>画笔<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;btn&quot;</span> <span class="attr">id</span>=<span class="string">&quot;rect&quot;</span>&gt;</span>矩形<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;btn&quot;</span>&gt;</span>圆形<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;btn&quot;</span>&gt;</span>线段粗细<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;btn&quot;</span>&gt;</span>画笔颜色<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">        <span class="comment">//获取所有按钮</span></span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> allBtn = <span class="built_in">document</span>.querySelectorAll(<span class="string">&quot;.btn&quot;</span>);</span></span><br><span class="line"><span class="javascript">        <span class="comment">//获取Canvas</span></span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">//设置Canvas宽度和高度</span></span></span><br><span class="line"><span class="javascript">        canvas.setAttribute(<span class="string">&quot;width&quot;</span>, canvas.offsetWidth);</span></span><br><span class="line"><span class="javascript">        canvas.setAttribute(<span class="string">&quot;height&quot;</span>, canvas.offsetHeight);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> huaban = &#123;  <span class="comment">//画笔对象</span></span></span><br><span class="line"><span class="javascript">            type: <span class="string">&quot;none&quot;</span>,</span></span><br><span class="line"><span class="javascript">            isDraw: <span class="literal">false</span>,</span></span><br><span class="line"><span class="javascript">            beginX: <span class="number">0</span>, <span class="comment">//开始位置</span></span></span><br><span class="line">            beginY: 0,</span><br><span class="line"><span class="javascript">            imageData:<span class="literal">null</span>,</span></span><br><span class="line"><span class="javascript">            <span class="comment">//绘制画笔</span></span></span><br><span class="line"><span class="javascript">            huabiFn: <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> x = e.pageX - canvas.offsetLeft;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> y = e.pageY - canvas.offsetTop;</span></span><br><span class="line">                ctx.beginPath();</span><br><span class="line"><span class="javascript">                ctx.arc(x, y, <span class="number">3</span>, <span class="number">0</span>, <span class="number">2</span> * <span class="built_in">Math</span>.PI);</span></span><br><span class="line">                ctx.fill();</span><br><span class="line">                ctx.closePath();</span><br><span class="line">            &#125;,</span><br><span class="line"><span class="javascript">            <span class="comment">//绘制矩阵</span></span></span><br><span class="line"><span class="javascript">            rectFn: <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> x = e.pageX - canvas.offsetLeft;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> y = e.pageY - canvas.offsetTop;</span></span><br><span class="line">                ctx.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);</span><br><span class="line"><span class="javascript">                <span class="function"><span class="title">if</span>(<span class="params">huaban.imageData!=<span class="literal">null</span></span>)</span>&#123;</span></span><br><span class="line">                    ctx.putImageData(huaban.imageData,0,0,0,0,canvas.offsetWidth, canvas.offsetHeight);</span><br><span class="line">                &#125;</span><br><span class="line">                ctx.beginPath();</span><br><span class="line">                ctx.rect(huaban.beginX, huaban.beginY, x - huaban.beginX, y - huaban.beginY);</span><br><span class="line"><span class="javascript">                <span class="comment">//ctx.fill();</span></span></span><br><span class="line">                ctx.stroke();</span><br><span class="line">                ctx.closePath();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">//设置画笔功能</span></span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> huabibtn = <span class="built_in">document</span>.getElementById(<span class="string">&quot;huabi&quot;</span>);</span></span><br><span class="line"><span class="javascript">        huabibtn.onclick = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="comment">//其他按钮去掉样式</span></span></span><br><span class="line"><span class="javascript">            allBtn.forEach(<span class="function"><span class="keyword">function</span> (<span class="params">item, i</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">                item.classList.remove(<span class="string">&quot;active&quot;</span>);</span></span><br><span class="line">            &#125;);</span><br><span class="line"><span class="javascript">            huabibtn.classList.add(<span class="string">&quot;active&quot;</span>);</span></span><br><span class="line"><span class="javascript">            huaban.type = <span class="string">&quot;huabi&quot;</span>;</span></span><br><span class="line">        &#125;;</span><br><span class="line"><span class="javascript">        <span class="comment">//设置画矩形功能</span></span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> rectBtn = <span class="built_in">document</span>.getElementById(<span class="string">&quot;rect&quot;</span>);</span></span><br><span class="line"><span class="javascript">        rectBtn.onclick = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="comment">//其他按钮去掉样式</span></span></span><br><span class="line"><span class="javascript">            allBtn.forEach(<span class="function"><span class="keyword">function</span> (<span class="params">item, i</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">                item.classList.remove(<span class="string">&quot;active&quot;</span>);</span></span><br><span class="line">            &#125;);</span><br><span class="line"><span class="javascript">            rectBtn.classList.add(<span class="string">&quot;active&quot;</span>);</span></span><br><span class="line"><span class="javascript">            huaban.type = <span class="string">&quot;rect&quot;</span>;</span></span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">//监听鼠标按下事件，允许画</span></span></span><br><span class="line"><span class="javascript">        canvas.onmousedown = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            huaban.isDraw = <span class="literal">true</span>;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">if</span> (huaban.type == <span class="string">&quot;rect&quot;</span>) &#123;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> x = e.pageX - canvas.offsetLeft;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> y = e.pageY - canvas.offsetTop;</span></span><br><span class="line"><span class="javascript">                huaban.beginX = x; <span class="comment">//更改起始点</span></span></span><br><span class="line">                huaban.beginY = y;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">//监听鼠标抬起事件，不允许画</span></span></span><br><span class="line"><span class="javascript">        canvas.onmouseup = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line">            huaban.imageData= ctx.getImageData(0,0,canvas.offsetWidth, canvas.offsetHeight);</span><br><span class="line"><span class="javascript">            huaban.isDraw = <span class="literal">false</span>;</span></span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">// 鼠标移动事件监听，开始绘制</span></span></span><br><span class="line"><span class="javascript">        canvas.onmousemove = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">if</span> (huaban.isDraw) &#123;  <span class="comment">//允许为true 可以画</span></span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> str = huaban.type + <span class="string">&#x27;Fn&#x27;</span>;</span></span><br><span class="line">                huaban[str](e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="验证码"><a href="#验证码" class="headerlink" title="验证码"></a>验证码</h2><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">style</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;mycanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;120&quot;</span> <span class="attr">height</span>=<span class="string">&quot;40&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">//封装成一个函数</span></span></span><br><span class="line"><span class="javascript">        <span class="function"><span class="keyword">function</span> <span class="title">YZM</span>(<span class="params">selector, w, h</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="comment">//随机数生成函数</span></span></span><br><span class="line"><span class="javascript">            <span class="function"><span class="keyword">function</span> <span class="title">rondomNum</span>(<span class="params">min, max</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">return</span> <span class="built_in">parseInt</span>(<span class="built_in">Math</span>.random() * (max - min) + min);</span></span><br><span class="line">            &#125;</span><br><span class="line"><span class="javascript">            <span class="comment">//随机生成颜色的函数</span></span></span><br><span class="line"><span class="javascript">            <span class="function"><span class="keyword">function</span> <span class="title">rondomColor</span>(<span class="params">min, max</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> r = rondomNum(min, max);</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> g = rondomNum(min, max);</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> b = rondomNum(min, max);</span></span><br><span class="line"><span class="javascript">                <span class="keyword">return</span> <span class="string">`rgb(<span class="subst">$&#123;r&#125;</span>,<span class="subst">$&#123;g&#125;</span>,<span class="subst">$&#123;b&#125;</span>)`</span>;</span></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">//获取Canvas</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> w = w;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> h = h;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> canvas = <span class="built_in">document</span>.getElementById(<span class="string">&quot;mycanvas&quot;</span>); <span class="comment">//画布</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">&quot;2d&quot;</span>);  <span class="comment">//画笔</span></span></span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">//在canvas上绘制背景颜色</span></span></span><br><span class="line">            ctx.fillStyle = rondomColor(180, 230);</span><br><span class="line">            ctx.fillRect(0, 0, w, h);</span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">// 生成随机字符串</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> pool = <span class="string">&#x27;ABCDEFGHIGKLIMNOPQRSTUVWXYZabcdefghijkopqrstuvwxvz1234567890&#x27;</span>;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> result = <span class="string">&quot;&quot;</span>;</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++) &#123;</span></span><br><span class="line"><span class="javascript">                <span class="comment">//取出随机字符串</span></span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> str = pool[rondomNum(<span class="number">0</span>, pool.length)];</span></span><br><span class="line"><span class="javascript">                <span class="comment">//随机字体大小</span></span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> font_size = rondomNum(<span class="number">18</span>, <span class="number">40</span>);</span></span><br><span class="line"><span class="javascript">                <span class="comment">//随机字体旋转角度</span></span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> font_angle = rondomNum(-<span class="number">30</span>, <span class="number">30</span>);</span></span><br><span class="line"><span class="javascript">                ctx.font = font_size + <span class="string">&#x27;px Simhei&#x27;</span>;</span></span><br><span class="line"><span class="javascript">                ctx.textBaseline = <span class="string">&#x27;top&#x27;</span>;  <span class="comment">//设置基线</span></span></span><br><span class="line"><span class="javascript">                <span class="comment">//设置字体随机填充颜色</span></span></span><br><span class="line">                ctx.fillStyle = rondomColor(80, 150);</span><br><span class="line"><span class="javascript">                ctx.save();  <span class="comment">//保存当前设置</span></span></span><br><span class="line">                ctx.translate(30 * i + 15, 15);</span><br><span class="line"><span class="javascript">                ctx.rotate(font_angle * <span class="built_in">Math</span>.PI / <span class="number">180</span>);</span></span><br><span class="line">                ctx.fillText(str, -10, -10);</span><br><span class="line"><span class="javascript">                ctx.restore(); <span class="comment">//恢复</span></span></span><br><span class="line"><span class="javascript">                result+=str;  <span class="comment">//连接验证码</span></span></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">// 随机生成干扰线</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span></span><br><span class="line">                ctx.beginPath();</span><br><span class="line">                ctx.moveTo(rondomNum(0, w), rondomNum(0, h));</span><br><span class="line">                ctx.lineTo(rondomNum(0, w), rondomNum(0, h));</span><br><span class="line">                ctx.strokeStyle = rondomColor(180, 230);</span><br><span class="line">                ctx.closePath();</span><br><span class="line">                ctx.stroke();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="comment">//随机产生40个小干扰圆点</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">40</span>; i++) &#123;</span></span><br><span class="line">                ctx.beginPath();</span><br><span class="line"><span class="javascript">                ctx.arc(rondomNum(<span class="number">0</span>, w), rondomNum(<span class="number">0</span>, h), <span class="number">1</span>, <span class="number">0</span>, <span class="number">2</span> * <span class="built_in">Math</span>.PI);</span></span><br><span class="line">                ctx.closePath();</span><br><span class="line">                ctx.fillStyle = rondomColor(150, 200);</span><br><span class="line">                ctx.fill();</span><br><span class="line">                ctx.stroke();</span><br><span class="line">            &#125;</span><br><span class="line"><span class="javascript">            <span class="keyword">return</span> result;  <span class="comment">//返回验证码</span></span></span><br><span class="line">        &#125;</span><br><span class="line"><span class="javascript">        <span class="comment">//调用函数</span></span></span><br><span class="line"><span class="javascript">        <span class="keyword">let</span> yzm = YZM(<span class="string">&#x27;#mycanvas&#x27;</span>, <span class="number">120</span>, <span class="number">40</span>); <span class="comment">//得到验证码</span></span></span><br><span class="line"><span class="javascript">        <span class="built_in">console</span>.log(yzm);</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">小李博客</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://xiaoliblog.cn">https://xiaoliblog.cn</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://xiaoliblog.cn" target="_blank">小李博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Canvas/">Canvas</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/xiaoliblog/image@76e609149105acb43a9f47548c4cdc694358041d/2021/02/24/7a395219eedbe9cb0204f24089256030.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.png" target="_blank"><img class="post-qr-code-img" src="/img/wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.png" target="_blank"><img class="post-qr-code-img" src="/img/alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/page/Nodejs01.html"><img class="prev-cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@2895ba074157927269b720f768c7eec8f888ef00/2021/02/27/f47a38e40ee25200927537ff8a913bfc.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Node.js🚀核心模块的使用</div></div></a></div><div class="next-post pull-right"><a href="/page/svg.html"><img class="next-cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@227b06ad5bfdfa8cc16d6e1c1210b66d7298179b/2021/02/23/dfbb5c46e951916f68ed9c1facae6e99.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">SVG矢量图</div></div></a></div></nav><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">小李博客</div><div class="author-info__description">越努力，越幸运！</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xiaoliblog"><i class="fab fa-github"></i><span>博主的GitHub首页</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/xiaoliblog" target="_blank" title="Gitee"><i class="iconfont icon-gitee card_icon_gitee"></i></a><a class="social-icon" href="https://space.bilibili.com/390969485" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili card_icon_bilibili"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2312057536&amp;site=CSDN&amp;menu=yes" target="_blank" title="QQ"><i class="iconfont icon-qq card_icon_qq"></i></a><a class="social-icon" href="https://github.com/xiaoliblog" target="_blank" title="GitHub"><i class="iconfont icon-git card_icon_git"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_43266250?spm=1010.2135.3001.5113" target="_blank" title="CSDN"><i class="iconfont icon-csdn card_icon_csdn"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">正在考研备考中💦</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Canvas%E7%AE%80%E4%BB%8B"><span class="toc-number">1.</span> <span class="toc-text">Canvas简介</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Canvas%E5%AE%9E%E4%BE%8B"><span class="toc-number">1.1.</span> <span class="toc-text">Canvas实例</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Canvas%E5%9F%BA%E7%A1%80%E7%BB%98%E5%88%B6"><span class="toc-number">2.</span> <span class="toc-text">Canvas基础绘制</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%B7%AF%E5%BE%84"><span class="toc-number">2.1.</span> <span class="toc-text">路径</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%BF%E6%AE%B5"><span class="toc-number">2.2.</span> <span class="toc-text">线段</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9C%86"><span class="toc-number">2.3.</span> <span class="toc-text">圆</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%87%E6%9C%AC"><span class="toc-number">2.4.</span> <span class="toc-text">文本</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Canvas%E5%B8%B8%E8%A7%81%E6%93%8D%E4%BD%9C"><span class="toc-number">3.</span> <span class="toc-text">Canvas常见操作</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%BE%E5%83%8F%E7%BB%98%E5%88%B6"><span class="toc-number">3.1.</span> <span class="toc-text">图像绘制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%86%E9%A2%91%E5%A4%84%E7%90%86"><span class="toc-number">3.2.</span> <span class="toc-text">视频处理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%98%E5%88%B6%E6%97%B6%E9%92%9F"><span class="toc-number">3.3.</span> <span class="toc-text">绘制时钟</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%AE%E5%88%AE%E5%8D%A1"><span class="toc-number">3.4.</span> <span class="toc-text">刮刮卡</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%94%BB%E6%9D%BF"><span class="toc-number">3.5.</span> <span class="toc-text">画板</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%AA%8C%E8%AF%81%E7%A0%81"><span class="toc-number">3.6.</span> <span class="toc-text">验证码</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/page/project01.html" title="前端实例🥳响应式网站首页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@c19917500ab083c77c7613263ba7ee74d5a08ae6/2021/04/30/469f30b141d73fa0fc4c962662d5813f.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="前端实例🥳响应式网站首页"/></a><div class="content"><a class="title" href="/page/project01.html" title="前端实例🥳响应式网站首页">前端实例🥳响应式网站首页</a><time datetime="2021-04-30T11:50:53.094Z" title="发表于 2021-04-30 19:50:53">2021-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/WeChatpay.html" title="微信支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@f2f670b92ea149650ffa7834354fc90284f2f44a/2021/04/29/5bdc9b381a06193d27cf2fb7c2fb608a.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="微信支付对接"/></a><div class="content"><a class="title" href="/page/WeChatpay.html" title="微信支付对接">微信支付对接</a><time datetime="2021-04-29T12:20:48.070Z" title="发表于 2021-04-29 20:20:48">2021-04-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Alipay.html" title="支付宝支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61a9b6a6e09e4bda38bb08e3104b717885beaee5/2021/04/29/c3fa51f9cf14e90d9e5a7aa8814dd041.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="支付宝支付对接"/></a><div class="content"><a class="title" href="/page/Alipay.html" title="支付宝支付对接">支付宝支付对接</a><time datetime="2021-04-27T16:00:00.000Z" title="发表于 2021-04-28 00:00:00">2021-04-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Pagination+PageHelper实现分页"/></a><div class="content"><a class="title" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页">Vue.js前端框架🎯Pagination+PageHelper实现分页</a><time datetime="2021-04-26T14:48:39.701Z" title="发表于 2021-04-26 22:48:39">2021-04-26</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Vue-Element-admin模版"/></a><div class="content"><a class="title" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版">Vue.js前端框架🎯Vue-Element-admin模版</a><time datetime="2021-04-19T16:00:00.000Z" title="发表于 2021-04-20 00:00:00">2021-04-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By 小李博客</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">🎯Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">🎉Butterfly</a></div><div class="footer_custom_text"><span><a style="margin-inline:5px" target="_blank" href="https://hexo.io/"><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为Hexo"></a><a style="margin-inline:5px" target="_blank" href="https://butterfly.js.org/"><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用butterfly"></a><a style="margin-inline:5px" target="_blank" href="https://www.jsdelivr.com/"><img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a><a style="margin-inline:5px" target="_blank" href="https://vercel.com/ "><img src="https://img.shields.io/badge/Hosted-Vercel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a><a style="margin-inline:5px" target="_blank" href="https://coding.net/ "><img src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a><a style="margin-inline:5px" target="_blank" href="https://github.com/"><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a><a style="margin-inline:5px" target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></span></div><div class="icp"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/"><img class="icp-icon" src="/img/icp.png" alt="ICP"/><span>湘ICP备2021002541号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script><script src="/js/main.js"></script><script defer src="/js/tw_cn.js"></script><script defer src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module" defer></script><script defer src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script defer src="/js/search/algolia.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    loader: {
      source: {
        '[tex]/amsCd': '[tex]/amscd'
      }
    },
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        addClass: [200,() => {
          document.querySelectorAll('mjx-container:not([display=\'true\']').forEach( node => {
            const target = node.parentNode
            if (!target.classList.contains('has-jax')) {
              target.classList.add('mathjax-overflow')
            }
          })
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: ''
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo@1.3.0/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script defer src="//lib.baomitu.com/jquery/3.5.1/jquery.min.js"></script><script defer src="https://myhkw.cn/api/player/160561664166" id="myhk" key="160561664166" m="1"></script><div><canvas id="snow" style="position:fixed;top:0;left:0;width:100%;height:100%;z-index:99999;pointer-events:none"></canvas></div><script>const notMobile = (!(navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)));</script><scrip async type="text/javascript" src="https://cdn.jsdelivr.net/gh/Candinya/Kratos-Rebirth@latest/source/js/snow.min.js"></scrip><scrip defer src="https://cdn.jsdelivr.net/npm/hexo-theme-volantis@latest/source/js/issues.min.js"></scrip><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><script>var gitcalendar = new Vue({
  el: '#gitcalendar',
  data: {
    simplemode: true, 
    user: 'xiaoliblog',
    fixed: 'fixed',
    px: 'px',
    x: '',
    y: '',
    span1: '',
    span2: '',
    month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthchange: [],
    oneyearbeforeday: '',
    thisday: '',
    amonthago: '',
    aweekago: '',
    weekdatacore: 0,
    datacore: 0,
    total: 0,
    datadate: '',
    data: [],
    positionplusdata: [],
    firstweek: [],
    lastweek: [],
    beforeweek: [],
    thisweekdatacore: 0,
    mounthbeforeday: 0,
    mounthfirstindex: 0,
    crispedges: 'crispedges',
    thisdayindex: 0,
    amonthagoindex: 0,
    amonthagoweek: [],
    firstdate: [],
    first2date: [],
    montharrbefore: [],
    monthindex: 0,
    color: ['#ebedf0', '#f1f8ff', '#dbedff', '#c8e1ff', '#79b8ff', '#2188ff', '#0366d6', '#005cc5', '#044289', '#032f62', '#05264c']
  },
  methods: {
    selectStyle(data, event) {
      document.querySelector('.angle-wrapper').style.display = 'block'
      this.span1 = data.date;
      this.span2 = data.count;
      this.x = event.clientX - 100;
      this.y = event.clientY - 60
    },
    outStyle() {
      document.querySelector('.angle-wrapper').style.display = 'none'
    },
    thiscolor(x) {
      if (x === 0) {
        let i = parseInt(x / 2);
        return this.color[0]
      } else if (x < 2) {
        return this.color[1]
      } else if (x < 20) {
        let i = parseInt(x / 2);
        return this.color[i]
      } else {
        return this.color[9]
      }
    },
  }
});
var apiurl = 'python-github-calendar-api-ruby.vercel.app' ? 'https://python-github-calendar-api-ruby.vercel.app/api?' : 'https://githubapi.ryanchristian.dev/user/'
var githubapiurl = apiurl + gitcalendar.user;
//canvas绘图
function responsiveChart() {
  let c = document.getElementById("gitcanvas");
  if (c) {
    let cmessage = document.getElementById("gitmessage");
    let ctx = c.getContext("2d");
    c.width = document.getElementById("gitcalendarcanvasbox").offsetWidth;
    let linemaxwitdh = 0.96 * c.width / gitcalendar.data.length;
    c.height = 9 * linemaxwitdh;
    let lineminwitdh = 0.8 * linemaxwitdh;
    let setposition = {
      x: 0.02 * c.width,
      y: 0.025 * c.width
    };
    for (let week in gitcalendar.data) {
      weekdata = gitcalendar.data[week];
      for (let day in weekdata) {
        let dataitem = {
          date: "",
          count: "",
          x: 0,
          y: 0
        };
        gitcalendar.positionplusdata.push(dataitem);
        ctx.fillStyle = gitcalendar.thiscolor(weekdata[day].count);
        setposition.y = Math.round(setposition.y * 100) / 100;
        dataitem.date = weekdata[day].date;
        dataitem.count = weekdata[day].count;
        dataitem.x = setposition.x;
        dataitem.y = setposition.y;
        ctx.fillRect(setposition.x, setposition.y, lineminwitdh, lineminwitdh);
        setposition.y = setposition.y + linemaxwitdh
      };
      setposition.y = 0.025 * c.width;
      setposition.x = setposition.x + linemaxwitdh
    };
    ctx.font = "600  Arial";
    ctx.fillStyle = '#aaa';
    ctx.fillText("日", 0, 1.9 * linemaxwitdh);
    ctx.fillText("二", 0, 3.9 * linemaxwitdh);
    ctx.fillText("四", 0, 5.9 * linemaxwitdh);
    ctx.fillText("六", 0, 7.9 * linemaxwitdh);
    let monthindexlist = c.width / 24;
    for (let index in gitcalendar.monthchange) {
      ctx.fillText(gitcalendar.monthchange[index], monthindexlist, 0.7 * linemaxwitdh);
      monthindexlist = monthindexlist + c.width / 12
    };
    cmessage.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
    };
    c.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
      getMousePos(c, event);
    };

    function getMousePos(canvas, event) {
      var rect = canvas.getBoundingClientRect();
      var x = event.clientX - rect.left * (canvas.width / rect.width);
      var y = event.clientY - rect.top * (canvas.height / rect.height);
      //console.log("x:"+x+",y:"+y);
      for (let item of gitcalendar.positionplusdata) {
        let lenthx = x - item.x;
        let lenthy = y - item.y;
        //console.log(lenthx,lenthy);
        if (0 < lenthx && lenthx < lineminwitdh) {
          if (0 < lenthy && lenthy < lineminwitdh) {
            //console.log(item.date,item.count)
            document.querySelector('.angle-wrapper').style.display = 'block'
            gitcalendar.span1 = item.date;
            gitcalendar.span2 = item.count;
            gitcalendar.x = event.clientX - 100;
            gitcalendar.y = event.clientY - 60
          }
        }
        //if(0< x - item.x <lineminwitdh&&0< y - item.y <lineminwitdh){
        //console.log(item.count,item.date);
        //}
      }
    }
  }
}
//数据统计算法
function addlastmonth() {
  if (gitcalendar.thisdayindex === 0) {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweekcore(48);
    gitcalendar.thisweekdatacore += gitcalendar.firstdate[6].count;
    gitcalendar.amonthago = gitcalendar.firstdate[6].date
  } else {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweek2core();
    gitcalendar.amonthago = gitcalendar.first2date[gitcalendar.thisdayindex - 1].date
  }
};

function thisweek2core() {
  for (let i = gitcalendar.thisdayindex - 1; i < gitcalendar.first2date.length; i++) {
    gitcalendar.thisweekdatacore += gitcalendar.first2date[i].count
  }
};

function thisweekcore(index) {
  for (let item of gitcalendar.data[index]) {
    gitcalendar.thisweekdatacore += item.count
  }
};

function addlastweek() {
  for (let item of gitcalendar.lastweek) {
    gitcalendar.weekdatacore += item.count
  }
};

function addbeforeweek() {
  for (let i = gitcalendar.thisdayindex; i < gitcalendar.beforeweek.length; i++) {
    gitcalendar.weekdatacore += gitcalendar.beforeweek[i].count
  }
};

function addweek(data) {
  if (gitcalendar.thisdayindex === 6) {
    gitcalendar.aweekago = gitcalendar.lastweek[0].date;
    addlastweek()
  } else {
    lastweek = data.contributions[51];
    gitcalendar.aweekago = lastweek[gitcalendar.thisdayindex + 1].date;
    addlastweek();
    addbeforeweek()
  }
}

fetch(githubapiurl)
  .then(data => data.json())
  .then(data => {
    gitcalendar.data = data.contributions;
    gitcalendar.total = data.total;
    gitcalendar.first2date = gitcalendar.data[48];
    gitcalendar.firstdate = gitcalendar.data[47];
    gitcalendar.firstweek = data.contributions[0];
    gitcalendar.lastweek = data.contributions[52];
    gitcalendar.beforeweek = data.contributions[51];
    gitcalendar.thisdayindex = gitcalendar.lastweek.length - 1;
    gitcalendar.thisday = gitcalendar.lastweek[gitcalendar.thisdayindex].date;
    gitcalendar.oneyearbeforeday = gitcalendar.firstweek[0].date;
    gitcalendar.monthindex = gitcalendar.thisday.substring(5, 7) * 1;
    gitcalendar.montharrbefore = gitcalendar.month.splice(gitcalendar.monthindex, 12 - gitcalendar.monthindex);
    gitcalendar.monthchange = gitcalendar.montharrbefore.concat(gitcalendar.month);
    addweek(data);
    addlastmonth();
    responsiveChart();
  })
  .catch(function(error) {
    console.log(error);
  });

//手机版更换为svg绘制
if (document.getElementById("gitcalendarcanvasbox").offsetWidth < 500) {
  gitcalendar.simplemode = false
}

//当改变窗口大小时重新绘制canvas
window.onresize = function() {
  if (gitcalendar.simplemode) responsiveChart()
}

//解决滚动滑轮时出现的标签显示
window.onscroll = function() {
  if (document.querySelector('.angle-wrapper')) {
    document.querySelector('.angle-wrapper').style.display = 'none'
  }
};</script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body></html>